# coding=utf-8
"""

2. 以Lena为原始图像，通过OpenCV使用Sobel及Canny算子检测，比较边缘检测结果。
结果分析：
Sobel算子检测由x轴，y轴分别计算然后合成的效果最佳，边缘检测较明显。
Canny算子边缘检测效果较明显，阈值二值化处理，极大值抑制使图像边缘与其他区域区分更加明显。
Sobel算子效果不错，Canny算子效果则更明显。

"""

import cv2 as cv

LenaFilename = r'lena.jpg'

img = cv.imread(LenaFilename)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

# Sobel 算子边缘检测
deltax = cv.Sobel(gray, cv.CV_32F, 1, 0)  # X方向的差异
deltay = cv.Sobel(gray, cv.CV_32F, 0, 1)  # Y方向的差异
adsX = cv.convertScaleAbs(deltax)
adsY = cv.convertScaleAbs(deltay)
dst = cv.addWeighted(adsX, 0.5, adsY, 0.5, 0)

cv.imshow("X", adsX)  # 运行结果:  https://gitee.com/skyrookieyu/csdn_ai25_week2/blob/master/2_1.JPG
cv.imshow("Y", adsY)  # 运行结果:  https://gitee.com/skyrookieyu/csdn_ai25_week2/blob/master/2_2.JPG
cv.imshow("Sobel", dst)  # 运行结果:  https://gitee.com/skyrookieyu/csdn_ai25_week2/blob/master/2_3.JPG

# Canny算子边缘检测
canny50 = cv.Canny(gray, 50, 120)
canny80 = cv.Canny(gray, 80, 120)
cv.imshow('Canny50_120', canny50)  # 运行结果:  https://gitee.com/skyrookieyu/csdn_ai25_week2/blob/master/2_4.JPG
cv.imshow('Canny80_120', canny80)  # 运行结果:  https://gitee.com/skyrookieyu/csdn_ai25_week2/blob/master/2_5.JPG

cv.waitKey()
cv.destroyAllWindows()
